<template>
  <div class="form-wrapper">
    <Form
      ref="baseForm"
      :model="baseForm"
      :rules="ruleValidate"
      :label-position="labelPosition"
      :label-width="labelWidth"
    >
      <fieldset class="line-field" id="course_info">
        <legend>课程基本信息</legend>
        <FormItem label="所属学院" prop="institute">
          <Input v-model="baseForm.institute" readonly placeholder="教师所属学院" />
        </FormItem>
        <FormItem label="教师姓名" prop="teacher_name">
          <Input v-model="baseForm.teacher_name" readonly placeholder="教师姓名" />
        </FormItem>
        <FormItem label="课程" prop="course_name">
            <Input v-model="baseForm.course_name" readonly placeholder="课程" />
        </FormItem>
        <FormItem label="实验教材" prop="textbook">
          <Input type="textarea" v-model="baseForm.textbook" clearable placeholder="实验指导书名称，编(写)者，出版社，出版日期" :autosize="{minRows: 2, maxRows: 6}"></Input>
        </FormItem>
        <FormItem label="班级信息" prop="classes">
          <Row :gutter="20" type="flex" justify="space-between" v-if="options.classes.length > 0">
            <div style="width: 100%; border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
              <Checkbox
                  :indeterminate="classesIndeterminate"
                  :value="classesCheckAll"
                  @click.prevent.native="handleCheckAllClasses">全选</Checkbox>
            </div>
            <CheckboxGroup v-model="baseForm.classes" style="width: 100%">
              <Col :xs="22" :sm="24" :md="11" v-for="(item, index) in options.classes" :key="index">
                <Checkbox :label="JSON.stringify(item)" style="margin-right: 20px">
                  {{ item.grade + item.major + item.sclass + "班" }}
                </Checkbox>
              </Col>
            </CheckboxGroup>
          </Row>
          <Alert v-else-if="loading.classes" show-icon type="info">加载班级中，请稍等...</Alert>
          <Alert v-else show-icon type="error">该课程暂无班级，请选择其他课程</Alert>
        </FormItem>
        <!-- <FormItem label="人数" prop="stu_num">
            <InputNumber :min="1" v-model="baseForm.stu_num" placeholder="总人数" style="width: 220px"></InputNumber>
        </FormItem> -->
      </fieldset>
    </Form>
    <div id="actions" class="text-center position-relative">
      <Poptip
        confirm
        title="确定修改该申请表的课程基本信息吗？"
        word-wrap
        width="180"
        @on-ok="handleSave"
        class="text-left"
        :options="popperOpts"
      >
        <Button type="success" :loading="loading.submit" class="mr-20">
          <span v-if="!loading.submit">提交表单</span>
          <span v-else>提交中...</span>
        </Button>
      </Poptip>
      <Poptip
        confirm
        title="数据将不可恢复，确定重置表单吗？"
        word-wrap
        width="180"
        @on-ok="handleReset"
        class="text-left"
        :options="popperOpts"
      >
        <Button style="margin-left: 8px" :disabled="loading.submit">重置表单</Button>
      </Poptip>
    </div>
  </div>
</template>
<script>
import { getFormDetailByCode, getClassesByCourse, updateCourseBase } from '@/api/apply-form'
export default {
  name: 'SaveCourseBase',
  data () {
    return {
      loading: {
        classes: true,
        submit: false
      },
      options: {
        classes: []
      },
      baseForm: {
        app_code: null,
        exp_type: 'COURSE',
        institute: null,
        teacher_code: null,
        teacher_name: null,
        course_code: null,
        course_name: null,
        textbook: null,
        classes: []
      },
      ruleValidate: {
        institute: [
          {required: true, message: '学院不能为空', trigger: 'change'}
        ],
        teacher_name: [
          {required: true, message: '教师不能为空', trigger: 'change'}
        ],
        course_name: [
          {required: true, message: '课程名字不能为空', trigger: 'change'}
        ],
        textbook: [
          {required: true, message: '实验教材详细情况不能为空', trigger: 'blur'}
        ],
        classes: [
          {required: true, type: 'array', min: 1, message: '至少选择一个班级', trigger: 'change'}
        ]
      },
      // 原子实验项目数据
      oriData: null,
      labelPosition: 'left',
      labelWidth: 100,
      // 全选班级的 indeterminate 状态，只负责样式控制
      classesIndeterminate: false,
      // 班级是否全选
      classesCheckAll: false,
      // Select选择器的下拉列表是否吸附，默认为true，吸附
      enabledPreventOverflow: false,
      popperOpts: {
        modifiers: {
          preventOverflow: {
            // 边界元素: scrollParent, window, viewport or any DOM element. 默认iview默认window
            boundariesElement: 'scrollParent'
          }
        }
      }
    }
  },
  props: {
    app_code: {
      type: String,
      default: null
    }
  },
  methods: {
    // 班级全选
    handleCheckAllClasses () {
      if (this.classesIndeterminate) {
        this.classesCheckAll = false
      } else {
        this.classesCheckAll = !this.classesCheckAll
      }
      this.classesIndeterminate = false
      if (this.classesCheckAll) {
        this.baseForm.classes = this.options.classes.map(item => {
          return JSON.stringify(item)
        })
      } else {
        this.baseForm.classes = []
      }
    },
    async getClassesOptions (courseCode, teacherCode) {
      this.loading.classes = true
      let response = await getClassesByCourse(courseCode, teacherCode)
      let res = response.data
      let options = []
      if (res.code && res.data.length > 0) {
        // 删掉不需要的键值对
        options = JSON.parse(JSON.stringify(res.data, ['grade', 'major', 'institute', 'sclass']))
      } else {
        this.$Notice.error({
          title: res.code ? '提示' : '抱歉，获取班级列表失败',
          desc: res.code ? '该课程暂无班级，请选择其他课程。' : res.info
        })
      }
      this.loading.classes = false
      return options
    },
    // 通过appCode获取历史申请表的详细信息
    async getPastFormByCode (code) {
      try {
        let res = await getFormDetailByCode(code)
        res = res.data
        if (res.code) {
          let formData = res.data
          try {
            this.fillFormByData(formData)
          } catch (error) {
            this.$Spin.hide()
            this.$emit('failFillFrom', '抱歉，获取登记表信息失败，请刷新后重试。' + error)
          }
        } else {
          this.$Spin.hide()
          this.$emit('failFillFrom', '抱歉，获取登记表信息失败，请刷新后重试。' + res.info)
        }
      } catch (error) {
        this.$Spin.hide()
        this.$emit('failFillFrom', '抱歉，获取登记表信息失败，请刷新后重试。' + error)
        console.log(error)
      }
    },
    // 通过从后台获取的数据填充到当前表单中
    async fillFormByData (data) {
      delete data.expBaseInfoItems
      delete data.stu_num
      try {
        this.options.classes = await this.getClassesOptions(data.course_code, data.teacher_code)
      } catch (error) {
        this.$Notice.error({
          title: '获取班级列表失败',
          desc: error
        })
        this.$Spin.hide()
      }
      for (let i = 0; i < data.classes.length; i++) {
        data.classes[i] = JSON.stringify(data.classes[i])
      }
      this.baseForm = JSON.parse(JSON.stringify(data))
      this.oriData = JSON.parse(JSON.stringify(data))
      this.$nextTick(() => {
        this.$Spin.hide()
      })
    },
    // 保存 新增/修改的单个实验
    handleSave () {
      this.loading.submit = true
      this.$refs['baseForm'].validate(async (valid) => {
        if (valid) {
          this.showSpinWithTip('提交表单中，请稍等...')
          try {
            let data = JSON.parse(JSON.stringify(this.baseForm))
            for (let i = 0; i < data.classes.length; i++) {
              data.classes[i] = JSON.parse(data.classes[i])
            }
            let response = await updateCourseBase(JSON.stringify(data))
            let res = response.data
            if (res.code) {
              this.$emit('saveSuccess')
            } else {
              this.$Notice.error({
                title: '抱歉，修改申请表课程基本信息失败',
                desc: res.info
              })
            }
          } catch (error) {
            console.log(error)
            this.$Notice.error({
              title: '提交失败',
              desc: '抱歉，修改申请表课程基本信息失败。' + error
            })
          }
          this.$Spin.hide()
        } else {
          this.$Notice.error({
            title: '提交失败',
            desc: '抱歉，无法提交，请先完善表单信息再提交。'
          })
        }
      })
    },
    // 重置表单
    handleReset () {
      this.$refs['baseForm'].resetFields()
      this.resetFormData()
    },
    resetFormData () {
      this.baseForm = JSON.parse(JSON.stringify(this.oriData))
    },
    // 显示带文字提示的Spin
    showSpinWithTip (tip) {
      this.$Spin.show({
        render: h => {
          return h('div', { class: 'ivu-spin-large' }, [
            h('span', {
              class: 'ivu-spin-dot',
              style: {
                display: 'inline-block'
              }
            }),
            h('div', tip)
          ])
        }
      })
    }
  },
  watch: {
    'baseForm.classes': function (val, oldVal) {
      if (val.length === this.options.classes.length && val.length > 0) {
        this.classesIndeterminate = false
        this.classesCheckAll = true
      } else if (val.length > 0) {
        this.classesIndeterminate = true
        this.classesCheckAll = false
      } else {
        this.classesIndeterminate = false
        this.classesCheckAll = false
      }
    }
  },
  mounted: function () {
    // 全局配置Notice组件的属性
    this.$Notice.config({
      top: window.innerHeight / 3
    })
    this.showSpinWithTip('加载申请表课程信息中...')
    this.getPastFormByCode(this.app_code)
  },
  beforeDestroy () {
    this.$Notice.destroy()
    this.$Modal.remove()
  }
}
</script>
